package com.easy.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class EasyController {

	@RequestMapping("/toLogin")
	public String toLoginPage() {
		return "login";
	}

	@RequestMapping("/doLogin")
	public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password,
			Model model) {
		// 获取当前用户
		Subject currentUser = SecurityUtils.getSubject();
		// 如果当前用户未进行认证
		if (!currentUser.isAuthenticated()) {
			// 将用户名和密码加密封装为token
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			try {
				// 执行登录
				currentUser.login(token);
			} catch (UnknownAccountException uae) { // 用户名不存在
				model.addAttribute("errorMsg", "用户名不存在！");
				return "login";
			} catch (IncorrectCredentialsException ice) { // 密码错误
				model.addAttribute("errorMsg", "密码错误！");
				return "login";
			}
		}
		return "index";
	}

	@RequestMapping("/toindex")
	public String toIndexPage() {
		return "index";
	}

	@RequestMapping("/loginout")
	public String loginOut() {
		SecurityUtils.getSubject().logout();
		// 重定向到登录页面或其他页面
		return "redirect:/login";
	}

	@RequiresRoles(value = { "User" })
	@RequestMapping("testRoleUser")
	@ResponseBody
	public String testRole() {
		return "testRole User success";
	}

	@RequiresRoles(value = { "Admin" })
	@RequestMapping("testRoleAdmin")
	@ResponseBody
	public String testAdminRole() {
		return "testRole Admin success";
	}

	@RequiresPermissions(value = { "View Dashboard" })
	@RequestMapping("testPermission")
	@ResponseBody
	public String testPermission() {
		return "testPermission success";
	}

	@RequiresPermissions(value = { "Edit User" })
	@RequestMapping("testEditPermission")
	@ResponseBody
	public String testEditPermission() {
		return "testPermission success";
	}

}
